

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>从一个 NullPointerException 探究 Java 的自动装箱拆箱机制 - 习武的个人博客</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="前天遇到了一个 NullPointerExceptio...">
  <meta name="author" content="习武">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/xiwu_see/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/xiwu_see/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/xiwu_see/images/icons/favicon-144x144.jpeg">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/xiwu_see/css/style.css">


  
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_s6x2xcokxrl.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: '/xiwu_see/images/theme/loading.gif'
      },
      donate: {
        enable: false,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '/xiwu_see/images/theme/welcome-image.jpg',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: false,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        model: 'simple'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 5.3.0"></head>

<body class="lock-screen">
  <div class="loading"></div>
  


  <nav class="navbar">
    <div class="left">
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
    </div>
    <div class="center">从一个 NullPointerException 探究 Java 的自动装箱拆箱机制</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
  </nav>

  

<nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/xiwu_see/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/xiwu_see/images/theme/theme-java-2.jpeg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">从一个 NullPointerException 探究 Java 的自动装箱拆箱机制</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>August 20, 2017</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>7480</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <p>前天遇到了一个 NullPointerException，触发的代码类似下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">long</span> <span class="hljs-title">test</span><span class="hljs-params">(<span class="hljs-keyword">long</span> value)</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> value;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Long value = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-comment">// ...</span><br>        test(value);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>main 方法里的代码实际上相当于调用 <code>test(null);</code>，为什么不直接这样写呢？因为编译不过，会报 <code>错误: 不兼容的类型: &lt;空值&gt;无法转换为long</code>。</p>
<h2 id="抛出问题"><a href="#抛出问题" class="headerlink" title="抛出问题"></a>抛出问题</h2><p>运行时提示 <code>test(value);</code> 这一行抛出 NullPointerException，但是看着以上代码会有些许困惑：以上代码里一个对象方法都没有调用啊，NullPointerException 从何而来？</p>
<h2 id="原因分析"><a href="#原因分析" class="headerlink" title="原因分析"></a>原因分析</h2><p>这时，如果留意到 test 方法接受的参数是 long 类型，而我们传入的是 Long 类型（虽然其实是 null），就会想到这会经历一次从类型 Long 到基本数据类型 long 的自动拆箱过程，那会不会是这个过程中抛出的 NullPointerException 呢？因为以前只知道 Java 为一些基础数据类型与对应的包装器类型之间提供了自动装箱拆箱机制，而并不知这机制的具体实现方法是怎么样的，正好学习一下。</p>
<p>用命令 <code>javap -c Test</code> 将以上代码编译出的 Test.class 文件进行反汇编，可以看到如下输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java">Compiled from <span class="hljs-string">&quot;Test.java&quot;</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Test</span><span class="hljs-params">()</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: aload_0<br>       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>       <span class="hljs-number">4</span>: <span class="hljs-keyword">return</span><br><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">long</span> <span class="hljs-title">test</span><span class="hljs-params">(<span class="hljs-keyword">long</span>)</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: lload_0<br>       <span class="hljs-number">1</span>: lreturn<br><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(java.lang.String[])</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: aconst_null<br>       <span class="hljs-number">1</span>: astore_1<br>       <span class="hljs-number">2</span>: aload_1<br>       3: invokevirtual #2                  // Method java/lang/Long.longValue:()J<br>       6: invokestatic  #3                  // Method test:(J)J<br>       <span class="hljs-number">9</span>: pop2<br>      <span class="hljs-number">10</span>: <span class="hljs-keyword">return</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p>从以上字节码及对应的注释可以看出，<code>test(value);</code> 这一行被编译后等同于如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">long</span> primitive = value.longValue();<br>test(promitive);<br></code></pre></td></tr></table></figure>
<p>相比实际代码，多出的 <code>long primitive = value.longValue();</code> 这一行看起来就是自动拆箱的过程了，而我们传入的 <code>value</code> 为 null，<code>value.longValue()</code> 会抛出 NullPointerException，一切就解释得通了。用更简洁的代码表达出了更丰富的含义，这就是所谓的语法糖了。</p>
<h2 id="证实猜想"><a href="#证实猜想" class="headerlink" title="证实猜想"></a>证实猜想</h2><p>那么我们上面得出的自动拆箱机制的结论是否正确呢？选择一种其它基本数据类型，比如 int，来佐证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Integer value = <span class="hljs-number">10</span>;<br>        <span class="hljs-keyword">int</span> primitive = value;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>反汇编后对应的字节码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java">Compiled from <span class="hljs-string">&quot;Test.java&quot;</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Test</span><span class="hljs-params">()</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: aload_0<br>       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>       <span class="hljs-number">4</span>: <span class="hljs-keyword">return</span><br><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(java.lang.String[])</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: bipush        <span class="hljs-number">10</span><br>       2: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;<br>       <span class="hljs-number">5</span>: astore_1<br>       <span class="hljs-number">6</span>: aload_1<br>       7: invokevirtual #3                  // Method java/lang/Integer.intValue:()I<br>      <span class="hljs-number">10</span>: istore_2<br>      <span class="hljs-number">11</span>: <span class="hljs-keyword">return</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p>由以上字节码我们可以印证下文里的知识点了。</p>
<h2 id="自动装箱与拆箱"><a href="#自动装箱与拆箱" class="headerlink" title="自动装箱与拆箱"></a>自动装箱与拆箱</h2><p>自动装箱与拆箱是 Java 1.5 引入的新特性，是一种语法糖。</p>
<p>在此之前，我们要创建一个值为 10 的 Integer 对象，只能写作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer value = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">10</span>);<br></code></pre></td></tr></table></figure>
<p>而现在，我们可以更方便地写为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer value = <span class="hljs-number">10</span>;<br></code></pre></td></tr></table></figure>
<h3 id="定义与实现机制"><a href="#定义与实现机制" class="headerlink" title="定义与实现机制"></a>定义与实现机制</h3><p><strong>自动装箱</strong>，是指从基本数据类型值到其对应的包装类对象的自动转换。比如 <code>Integer value = 10;</code>，是通过调用 Integer.valueOf 方法实现转换的。</p>
<p><strong>自动拆箱</strong>，是指从包装类对象到其对应的基本数据类型值的自动转换。比如 <code>int primitive = value;</code>，是通过调用 Integer.intValue 方法实现转换的。</p>
<table>
<thead>
<tr>
<th>基本数据类型</th>
<th>包装类型</th>
<th>装箱方法</th>
<th>拆箱方法</th>
</tr>
</thead>
<tbody><tr>
<td>boolean</td>
<td>Boolean</td>
<td>Boolean.valueOf(boolean)</td>
<td>Boolean.booleanValue()</td>
</tr>
<tr>
<td>byte</td>
<td>Byte</td>
<td>Byte.valueOf(byte)</td>
<td>Byte.byteValue()</td>
</tr>
<tr>
<td>char</td>
<td>Character</td>
<td>Character.valueOf(char)</td>
<td>Character.charValue()</td>
</tr>
<tr>
<td>short</td>
<td>Short</td>
<td>Short.valueOf(short)</td>
<td>Short.shortValue()</td>
</tr>
<tr>
<td>int</td>
<td>Integer</td>
<td>Integer.valueOf(int)</td>
<td>Integer.intValue()</td>
</tr>
<tr>
<td>long</td>
<td>Long</td>
<td>Long.valueOf(long)</td>
<td>Long.longValue()</td>
</tr>
<tr>
<td>float</td>
<td>Float</td>
<td>Float.valueOf(float)</td>
<td>Float.floatValue()</td>
</tr>
<tr>
<td>double</td>
<td>Double</td>
<td>Double.valueOf(double)</td>
<td>Double.doubleValue()</td>
</tr>
</tbody></table>
<h3 id="发生时机"><a href="#发生时机" class="headerlink" title="发生时机"></a>发生时机</h3><p>自动装箱与拆箱主要发生在以下四种时机：</p>
<ol>
<li><p>赋值时；</p>
</li>
<li><p>比较时；</p>
</li>
<li><p>算术运算时；</p>
</li>
<li><p>方法调用时。</p>
</li>
</ol>
<h3 id="常见应用场景"><a href="#常见应用场景" class="headerlink" title="常见应用场景"></a>常见应用场景</h3><p><strong>Case 1:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer value = <span class="hljs-number">10</span>; <span class="hljs-comment">// 自动装箱（赋值时）</span><br><br><span class="hljs-keyword">int</span> primitive = value; <span class="hljs-comment">// 自动拆箱（方法调用时）</span><br></code></pre></td></tr></table></figure>
<p><strong>Case 2:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer value = <span class="hljs-number">1000</span>;<br><span class="hljs-comment">// ...</span><br><span class="hljs-keyword">if</span> (value &lt;= <span class="hljs-number">1000</span>) &#123; <span class="hljs-comment">// 自动拆箱（比较时）</span><br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p><strong>Case 3:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;Integer&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>list.add(<span class="hljs-number">10</span>); <span class="hljs-comment">// 自动装箱（方法调用时）</span><br><br><span class="hljs-keyword">int</span> i = list.get(<span class="hljs-number">0</span>); <span class="hljs-comment">// 自动拆箱（赋值时）</span><br></code></pre></td></tr></table></figure>
<p><em>注：集合（Collections）里不能直接放入原始类型，集合只接收对象。</em></p>
<p><strong>Case 4:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">ThreadLocal&lt;Integer&gt; local = <span class="hljs-keyword">new</span> ThreadLocal&lt;Integer&gt;();<br>local.set(<span class="hljs-number">10</span>); <span class="hljs-comment">// 自动装箱（方法调用时）</span><br><br><span class="hljs-keyword">int</span> i = local.get(); <span class="hljs-comment">// 自动拆箱（赋值时）</span><br></code></pre></td></tr></table></figure>
<p><em>注：ThreadLocal 不能存储基本数据类型，只接收引用类型。</em></p>
<p><strong>Case 5:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">(Integer value)</span> </span>&#123;<br>    <span class="hljs-comment">//</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span> </span>&#123;<br>    <span class="hljs-comment">//</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> </span>&#123;<br>    fun1(<span class="hljs-number">10</span>); <span class="hljs-comment">// 自动装箱（方法调用时）</span><br><br>    Integer value = <span class="hljs-number">10</span>;<br>    fun2(value); <span class="hljs-comment">// 自动拆箱（方法调用时）</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p><strong>Case 6:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer v1 = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">10</span>);<br>Integer v2 = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">20</span>);<br><span class="hljs-keyword">int</span> v3 = <span class="hljs-number">30</span>;<br><br><span class="hljs-keyword">int</span> sum = v1 + v2; <span class="hljs-comment">// 自动拆箱（算术运算时）</span><br>sum = v1 + <span class="hljs-number">30</span>; <span class="hljs-comment">// 自动拆箱（算术运算时）</span><br></code></pre></td></tr></table></figure>
<h3 id="相关知识点"><a href="#相关知识点" class="headerlink" title="相关知识点"></a>相关知识点</h3><h4 id="比较"><a href="#比较" class="headerlink" title="比较"></a>比较</h4><p>除 <code>==</code> 以外，包装类对象与基本数据类型值的比较，包装类对象与包装类对象之间的比较，都是自动拆箱后对基本数据类型值进行比较，所以，<strong>要注意这些类型间进行比较时自动拆箱可能引发的 NullPointerException</strong>。</p>
<p><code>==</code> 比较特殊，因为可以用于判断左右是否为同一对象，所以两个包装类对象之间 <code>==</code>，会用于判断是否为同一对象，而不会进行自动拆箱操作；包装类对象与基本数据类型值之间 <code>==</code>，会自动拆箱。</p>
<p>示例代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer v1 = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">10</span>);<br>Integer v2 = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">20</span>);<br><br><span class="hljs-keyword">if</span> (v1 &lt; v2) &#123; <span class="hljs-comment">// 自动拆箱</span><br>    <span class="hljs-comment">// ...</span><br>&#125;<br><br><span class="hljs-keyword">if</span> (v1 == v2) &#123; <span class="hljs-comment">// 不拆箱</span><br>    <span class="hljs-comment">// ...</span><br>&#125;<br><br><span class="hljs-keyword">if</span> (v1 == <span class="hljs-number">10</span>) &#123; <span class="hljs-comment">// 自动拆箱</span><br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h4 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h4><p>Java 为整型值包装类 Byte、Character、Short、Integer、Long 设置了缓存，用于存储一定范围内的值，详细如下：</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>缓存值范围</th>
</tr>
</thead>
<tbody><tr>
<td>Byte</td>
<td>-128 ~ 127</td>
</tr>
<tr>
<td>Character</td>
<td>0 ~ 127</td>
</tr>
<tr>
<td>Short</td>
<td>-128 ~ 127</td>
</tr>
<tr>
<td>Integer</td>
<td>-128 ~ 127（可配置）</td>
</tr>
<tr>
<td>Long</td>
<td>-128 ~ 127</td>
</tr>
</tbody></table>
<p>在一些情况下，比如自动装箱时，如果值在缓存值范围内，将不创建新对象，直接从缓存里取出对象返回，比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer v1 = <span class="hljs-number">10</span>;<br>Integer v2 = <span class="hljs-number">10</span>;<br>Integer v3 = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">10</span>);<br>Integer v4 = <span class="hljs-number">128</span>;<br>Integer v5 = <span class="hljs-number">128</span>;<br>Integer v6 = Integer.valueOf(<span class="hljs-number">10</span>);<br><br>System.out.println(v1 == v2); <span class="hljs-comment">// true</span><br>System.out.println(v1 == v3); <span class="hljs-comment">// false</span><br>System.out.println(v4 == v5); <span class="hljs-comment">// false</span><br>System.out.println(v1 == v6); <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>
<p><strong>缓存实现机制：</strong></p>
<p>这里使用了设计模式享元模式。</p>
<p>以 Short 类实现源码为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// ...</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Short</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Number</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Comparable</span>&lt;<span class="hljs-title">Short</span>&gt; </span>&#123;<br>    <span class="hljs-comment">// ...</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ShortCache</span> </span>&#123;<br>        <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ShortCache</span><span class="hljs-params">()</span></span>&#123;&#125;<br><br>        <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Short cache[] = <span class="hljs-keyword">new</span> Short[-(-<span class="hljs-number">128</span>) + <span class="hljs-number">127</span> + <span class="hljs-number">1</span>];<br><br>        <span class="hljs-keyword">static</span> &#123;<br>            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; cache.length; i++)<br>                cache[i] = <span class="hljs-keyword">new</span> Short((<span class="hljs-keyword">short</span>)(i - <span class="hljs-number">128</span>));<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">// ...</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Short <span class="hljs-title">valueOf</span><span class="hljs-params">(<span class="hljs-keyword">short</span> s)</span> </span>&#123;<br>        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> offset = <span class="hljs-number">128</span>;<br>        <span class="hljs-keyword">int</span> sAsInt = s;<br>        <span class="hljs-keyword">if</span> (sAsInt &gt;= -<span class="hljs-number">128</span> &amp;&amp; sAsInt &lt;= <span class="hljs-number">127</span>) &#123; <span class="hljs-comment">// must cache</span><br>            <span class="hljs-keyword">return</span> ShortCache.cache[sAsInt + offset];<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Short(s);<br>    &#125;<br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p>在第一次调用到 <code>Short.valueOf(short)</code> 方法时，将创建 -128 ~ 127 对应的 256 个对象缓存到堆内存里。</p>
<p>这种设计，在频繁用到这个范围内的值的时候效率较高，可以避免重复创建和回收对象，否则有可能闲置较多对象在内存中。</p>
<h4 id="使用不当的情况"><a href="#使用不当的情况" class="headerlink" title="使用不当的情况"></a>使用不当的情况</h4><p>自动装箱和拆箱这种语法糖为我们写代码带来了简洁和便利，但如果使用不当，也有可能带来负面影响。</p>
<ol>
<li><p>性能的损耗</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer sum = <span class="hljs-number">0</span>;<br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1000</span>; i &lt; <span class="hljs-number">5000</span>; i++) &#123;<br>    <span class="hljs-comment">// 1. 先对 sum 进行自动拆箱</span><br>    <span class="hljs-comment">// 2. 加法</span><br>    <span class="hljs-comment">// 3. 自动装箱赋值给 sum，无法命中缓存，会 new Integer(int)</span><br>    sum = sum + i;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在循环过程中会分别调用 4000 次 Integer.intValue() 和 Integer.valueOf(int)，并 new 4000 个 Integer 对象，而这些操作将 sum 的类型改为 int 即可避免，节约运行时间和空间，提升性能。</p>
</li>
<li><p>java.lang.NullPointerException</p>
<p>尝试对一个值为 null 的包装类对象进行自动拆箱，就有可能造成 NullPointerException。</p>
<p>比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer v1 = <span class="hljs-keyword">null</span>;<br><span class="hljs-keyword">int</span> v2 = v1; <span class="hljs-comment">// NullPointerException</span><br><br><span class="hljs-keyword">if</span> (v1 &gt; <span class="hljs-number">10</span>) &#123; <span class="hljs-comment">// NullPointerException</span><br>    <span class="hljs-comment">// ...</span><br>&#125;<br><br><span class="hljs-keyword">int</span> v3 = v1 + <span class="hljs-number">10</span>; <span class="hljs-comment">// NullPointerException</span><br></code></pre></td></tr></table></figure>
<p>还有一种更隐蔽的情形，感谢 <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhou-shao-68-55">@周少</a> 补充：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-keyword">long</span> value = <span class="hljs-keyword">true</span> ? <span class="hljs-keyword">null</span> : <span class="hljs-number">1</span>; <span class="hljs-comment">// NullPointerException</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>这实际上还是对一个值为 null 的 Long 类型进行自动拆箱，反汇编代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java">Compiled from <span class="hljs-string">&quot;Test.java&quot;</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Test</span><span class="hljs-params">()</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: aload_0<br>       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>       <span class="hljs-number">4</span>: <span class="hljs-keyword">return</span><br><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(java.lang.String[])</span></span>;<br>    Code:<br>       <span class="hljs-number">0</span>: aconst_null<br>       1: checkcast     #2                  // class java/lang/Long<br>       4: invokevirtual #3                  // Method java/lang/Long.longValue:()J<br>       <span class="hljs-number">7</span>: lstore_1<br>       <span class="hljs-number">8</span>: <span class="hljs-keyword">return</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2></li>
</ol>
<ul>
<li><a target="_blank" rel="noopener" href="http://droidyue.com/blog/2015/04/07/autoboxing-and-autounboxing-in-java/index.html">Java中的自动装箱与拆箱</a></li>
<li><a target="_blank" rel="noopener" href="http://www.cnblogs.com/dolphin0520/p/3780005.html">深入剖析Java中的装箱和拆箱</a></li>
</ul>

      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>习武</li>
    <li><strong>本文链接：</strong><a href="https://gitee.com/xiwu123/xiwu_see.git/2017/08/20/Java/java-auto-boxing-unboxing/index.html" title="https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2017&#x2F;08&#x2F;20&#x2F;Java&#x2F;java-auto-boxing-unboxing&#x2F;index.html">https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2017&#x2F;08&#x2F;20&#x2F;Java&#x2F;java-auto-boxing-unboxing&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本博客所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/xiwu_see/tags/Java-%E8%87%AA%E5%8A%A8%E8%A3%85%E7%AE%B1-%E8%87%AA%E5%8A%A8%E6%8B%86%E7%AE%B1/" rel="tag">Java, 自动装箱, 自动拆箱</a></li></ul> 

        
  <nav class="nav">
    <a href="/xiwu_see/2017/10/14/Andriod/guanggoo-android-app/"><i class="iconfont iconleft"></i>发布一款光谷社区第三方 Android App</a>
    <a href="/xiwu_see/2017/02/19/%E5%8D%9A%E5%AE%A2%E6%96%87%E7%AB%A0/the-kite-runner/">读书：追风筝的人<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8A%9B%E5%87%BA%E9%97%AE%E9%A2%98"><span class="toc-text">抛出问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E5%9B%A0%E5%88%86%E6%9E%90"><span class="toc-text">原因分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%81%E5%AE%9E%E7%8C%9C%E6%83%B3"><span class="toc-text">证实猜想</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E8%A3%85%E7%AE%B1%E4%B8%8E%E6%8B%86%E7%AE%B1"><span class="toc-text">自动装箱与拆箱</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E4%B8%8E%E5%AE%9E%E7%8E%B0%E6%9C%BA%E5%88%B6"><span class="toc-text">定义与实现机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E7%94%9F%E6%97%B6%E6%9C%BA"><span class="toc-text">发生时机</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-text">常见应用场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="toc-text">相关知识点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-text">参考</span></a></li></ol>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=756364924 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://github.com/xiwuxisheng "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="756364924@qq.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
    <div class="scrollbar j-scrollbar">
  <div class="scrollbar-current j-scrollbar-current"></div>
</div>
  
  
    
<script src="/xiwu_see/js/color-mode.js"></script>

  
</body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>



  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>








<script src="/xiwu_see/js/utils.js"></script>
<script src="/xiwu_see/js/script.js"></script>





  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>